import { defineStore } from 'pinia'
import { useToast } from '@/components'
import { AxiosError } from 'axios'
import $http from '@/services/Http'
import { md5 } from '@/services/crypto'
import $router from '@/router'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('application', () => {
  const $toast = useToast()

  const msg = {
    success(detail) {
      $toast.add({ severity: 'success', summary: 'Success', detail, life: 3000 })
    },
    error(detail) {
      $toast.add({ severity: 'error', summary: 'Error', detail, life: 3000 })
    },
    warn(detail) {
      $toast.add({ severity: 'warn', summary: 'Warn', detail, life: 3000 })
    },
    info(detail) {
      $toast.add({ severity: 'info', summary: 'Infor', detail, life: 3000 })
    }
  }

  function callApi(url, method = 'get', ...rest) {
    return $http[method](url, ...rest) //.catch(catchHttpError)
  }

  function regist(body = {}) {
    body.pwd = md5(body.pwd).toString()
    return callApi('/regist', 'post', body)
  }

  function login({ un, pwd }) {
    return callApi('/login', 'post', { un, pwd: md5(pwd).toString() }).then((resp) => {
      const {
        data: {
          success,
          list: { data, token }
        }
      } = resp
      if (success) {
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(data))
      }

      return resp
    })
  }

  function logout() {
    console.log('logout!!')
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    $router.replace('/')
    location.reload()
  }

  function getUser() {
    if (localStorage.getItem('user')) {
      return JSON.parse(localStorage.getItem('user'))
    }
    return false
  }

  const user = computed(getUser)

  function catchHttpError(res) {
    if (res instanceof AxiosError) {
      const { response } = res

      if (!response?.data?.result) {
        msg.error(response.data.msg)
      } else {
        msg.error(res.message)
      }
    }
    return res
  }

  return { msg, catchHttpError, callApi, regist, login, logout, getUser, user }
})
